import pickle,base64
from django_redis import get_redis_connection


def merge_carts_cookie_redis(user,request,response):
    """合并购物车的时候已cookies中的数据为主"""
    cart_str = request.COOKIES.get('carts')
    if cart_str is None:
        return response

    cart_str_bytes = cart_str.encode()
    cart_dict_bytes = base64.b64decode(cart_str_bytes)
    cart_dict = pickle.loads(cart_dict_bytes)

    """
    {
        "sku_id1":{
            "count":"1",
            "selected":"True"
        },
        "sku_id3":{
            "count":"3",
            "selected":"False"
        }
    }
    """
    new_dict = {}
    new_selected_add = []
    new_selected_rem = []

    for sku_id, cookie_dict in cart_dict.items():
        # 构建新的字典数据，在redis中作为filed和value
        new_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            new_selected_add.append(sku_id)
        else:
            new_selected_rem.remove(sku_id)

    # 同步保存数据到redis的数据库中
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()

    pl.hmset('carts_%s' % user.id, new_dict)

    if new_selected_add:
        pl.sadd('selected_%s' % user.id, *new_selected_add)

    if new_selected_rem:
        pl.srem('selected_%s' % user.id, *new_selected_rem)

    pl.execute()

    response.delete_cookie('carts')

    return response